<template>
  <div class="search">
    <!-- 搜索表单 -->
    <form @submit.prevent="handleSearch" class="search">
      <el-input
        v-model="input"
        style="width: 80%; margin: 20px 0 10px 0"
        placeholder="请输入关键词"
        clearable
      />
      <el-button native-type="submit" type="primary" style="margin: 20px 0 0 10px">搜索</el-button>
    </form>
  </div>
  <div class="tag_search">
    <!-- 标签选择器 -->
    <div class="check_option">
      <span style="margin-right: 10px">标签</span>
      <el-select
        v-model="tag_value"
        filterable
        multiple
        placeholder="请选择标签"
        style="width: 240px"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.label"
        />
      </el-select>
    </div>
    <!-- 时间筛选器 -->
    <div class="block">
      <span style="margin-right: 10px">时间筛选</span>
      <el-date-picker
        v-model="timeRange"
        type="daterange"
        start-placeholder="开始时间"
        end-placeholder="结束时间"
        value-format="YYYY-MM-DD"
        @change="handleSearch"
      />
    </div>
  </div>
  <!-- 无限滚动 -->
  <div class="post_content" v-infinite-scroll="loadMorePosts">
    <div
      class="post_card"
      v-for="post in posts"
      :key="post.id"
      @click="handlePostClick(post)"
    >
      <div class="post_left">
        <div class="img">
          <img :src="post.userAvatar" alt="头像" />
        </div>
        <span class="autor">{{ post.username }}</span>
      </div>
      <div class="post_middle">
        <h3 class="title">{{ post.title }}</h3>
        <span class="time">{{ formatDate(post.createdAt) }}</span>
      </div>
      <div class="post_right">
        <span class="like">
          <i class="fas fa-heart"></i> 点赞 {{ post.likeCount }}
        </span>
        <span class="comment">
          <i class="fas fa-comment"></i> 评论{{post.commentCount}}
        </span>
      </div>
    </div>
    <!-- 加载提示 -->
    <div v-if="loading" class="loading">加载中...</div>
    <div v-if="noMore" class="no-more">没有更多数据了</div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue';
import { API_BASE_URL } from '@/config/config.js';
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter, useRoute } from 'vue-router';

// 路由与状态变量
const route = useRoute();
const router = useRouter();
const posts = ref([]);
const input = ref('');
const tag_value = ref([]);
const timeRange = ref([]);

// 分页与加载状态
const page = ref(1);
const pageSize = ref(3);
const total = ref(0);
const loading = ref(false);
const noMore = ref(false);

// 标签选项
const options = ref([]);

// 格式化时间
const formatDate = (dateString) => {
  const date = new Date(dateString);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

// 提交搜索表单时重置页码并搜索
const handleSearch = async () => {
  page.value = 1; // 重置页码为第一页
  pageSize.value = 10; // 重置每页条数为 10
  posts.value = []; // 清空当前帖子
  noMore.value = false; // 重置 "没有更多数据" 状态
  await getPosts(false); // 触发搜索

  // 如果数据不足以撑满容器，强制加载下一页
  if (posts.value.length < pageSize.value && !noMore.value) {
    loadMorePosts();
  }
};



// 调用查询帖子的接口
const getPosts = async (isLoadMore = false) => {
  const GET_POSTS_URL = `${API_BASE_URL}/posts/search`;

  try {
    loading.value = true; // 开始加载

    // 请求参数
    const params = {
      keyword: input.value?.trim() || '', // 关键词
      tagName: Array.isArray(tag_value.value) ? tag_value.value.join(',') : '', // 标签名
      page: page.value,
      pageSize: pageSize.value, // 每页条数
    };

    // 如果时间范围存在，传递时间参数
    if (timeRange.value && timeRange.value.length === 2) {
      const [startTime, endTime] = timeRange.value;
      params.timeRange = startTime === endTime ? startTime : `${startTime},${endTime}`;
    }

    // 请求后端接口
    const response = await axios.get(GET_POSTS_URL, { params });

    if (response.data.code === 200) {
      const { posts: newPosts, total: totalPosts } = response.data.data;

      total.value = totalPosts; // 更新总数据量

      if (!isLoadMore) {
        // 如果是新搜索，覆盖数据并重置页码
        posts.value = newPosts;
        page.value = 2; // 下一次加载应该从第 2 页开始
      } else {
        // 如果是加载更多，追加数据
        posts.value = [...posts.value, ...newPosts];
        page.value += 1; // 页码递增
      }
      // 判断是否加载完所有数据
      noMore.value = posts.value.length >= total.value || newPosts.length === 0;
    } else {
      ElMessage.error(`查询失败，错误码：${response.data.code}`);
    }
  } catch (error) {
    ElMessage.error('查询帖子失败：' + error.message);
  }
  finally {
    loading.value = false; // 确保 loading 状态被重置
  }
};

// 无限滚动加载
const loadMorePosts = () => {
  // 如果正在加载数据或已经没有更多数据，直接返回
  if (loading.value || noMore.value) return;

  // 动态调整 pageSize 的值
  pageSize.value = 5; // 每次加载 5 条数据
  getPosts(true); // 调用 getPosts 方法，加载更多数据
};


// 获取所有帖子分类
const getTagName = async () => {
  const GET_TAP_URL = `${API_BASE_URL}/tags/all`;
  try {
    const response = await axios.get(GET_TAP_URL);
    if (response.data.code === 200) {
      options.value = response.data.data.map((tag) => ({
        label: tag.name,
        value: tag.id,
      }));
    }
  } catch (error) {
    ElMessage.error('查询失败' + error.message);
  }
};

// 点击帖子打开详情页
const handlePostClick = (post) => {
  router.push({ name: 'Post_detail', params: { id: post.id, userId: post.userId } });
};

// 路由参数变化时自动搜索
watch(
  () => route.params.tag_name,
  (newTagName) => {
    if (newTagName) {
      tag_value.value = [newTagName];
      handleSearch();
    }
  },
  { immediate: true }
);

// 初始化加载
onMounted(() => {
  if (route.params.tag_name) {
    tag_value.value = [route.params.tag_name];
  }
  handleSearch(); // 初次加载时触发搜索
  getTagName(); // 加载标签数据
});
</script>

<style scoped>
/* 博客卡片容器样式 */
.post_content {
  width: 100%;
  height: 80vh;
  box-sizing: border-box;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px;
  background-color: white;
  position: relative;
  top: 10%;
  overflow-y: auto;
}

/* 博客卡片的样式 */
.post_card {
  width: calc(33.33% - 10px);
  height: 150px; /* 卡片高度 */
  background-color: white;
  border: 1px solid #dddddd;
  border-radius: 8px;
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transition: box-shadow 0.3s ease;
}

.post_card:hover {
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

.post_left {
  display: flex;
  align-items: center;
}

.img {
  width: 40px;
  height: 40px;
  overflow: hidden;
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  justify-content: center;
  align-items: center;
  margin-right: 10px;
}

.img img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  object-position: center;
}

.post_middle {
  flex: 1;
  margin: 10px 0;
}

.title {
  font-size: 16px;
  margin: 0;
  color: #333;
}

.time {
  font-size: 12px;
  color: #999;
}

.post_right {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.like,
.comment {
  font-size: 12px;
  color: #666;
}

/* 图标样式 */
.fas {
  margin-right: 2px;
  font-size: 14px;
  color: #666;
}

.fa-heart {
  color: #ff6b6b;
}

.fa-comment {
  color: #666;
}

.search {
  width: 100%;
  display: flex;
  justify-content: center;
}

.block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
  margin-left: 150px;
}

.block:last-child {
  border-right: none;
}

.block .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}
.tag_search {
  display: flex;
  justify-content: center;
  align-items: center;
}

.check_option {
  margin: 10px;
  display: flex;
  position: absolute;
  left: 10%;
}

/* 加载提示样式 */
.loading,
.no-more {
  text-align: center;
  padding: 10px;
  color: #666;
  width: 100%;
}
</style>
